package page

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shimmer/neusoft_club_backend/controllers/cons"
	"shimmer/neusoft_club_backend/dao/domain"
	"shimmer/neusoft_club_backend/middlewares/auth_middleware"
	"shimmer/neusoft_club_backend/services"
	"shimmer/neusoft_club_backend/services/club_service"
	"shimmer/neusoft_club_backend/services/errs"
)

// @Summary 创建/更新社团页面
// @Description 社团页面只能存在一个，所以当已经创建之后就自动变为更新
// @Tags 社团
// @Param clubID path integer true "社团ID"
// @Param page body club_service.UpsertClubPageReq true "页面内容"
// @Success 200 {object} domain.ClubPageDTO
// @Router /api/club/{clubID}/page [post]
func upsertClubPage(c *gin.Context) {
	user, err := domain.GetUserFromContext(c)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	clubBinding := &cons.ClubUriParamBinding{}
	if err = c.ShouldBindUri(clubBinding); err != nil {
		services.AbortWithError(c, err)
		return
	}
	isOwner, err := club_service.CheckIsClubOwner(user.ID, clubBinding.ClubID)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	if !isOwner {
		services.AbortWithError(c, errs.ErrIsNotClubMember)
		return
	}
	req := &club_service.UpsertClubPageReq{}
	if err = c.ShouldBind(req); err != nil {
		services.AbortWithError(c, err)
		return
	}
	res, err := club_service.UpsertClubPageByClubID(clubBinding.ClubID, req)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	c.JSON(http.StatusOK, res)
}

// @Summary 获取社团页面
// @Description
// @Tags 社团
// @Param clubID path integer true "社团ID"
// @Success 200 {object} domain.ClubPageDTO
// @Router /api/club/{clubID}/page [get]
func getClubPage(c *gin.Context) {
	clubBinding := &cons.ClubUriParamBinding{}

	if err := c.ShouldBindUri(clubBinding); err != nil {
		services.AbortWithError(c, err)
		return
	}
	page, err := club_service.GetClubPageByClubID(clubBinding.ClubID)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	c.JSON(http.StatusOK, page)
}

func ConfigureClubPageController(r *gin.RouterGroup) {
	r.POST("/", auth_middleware.AuthLoginMiddleware(), upsertClubPage)
	r.GET("/", getClubPage)
}
